/**********************************************************
 *
 *                      根据ID读取组态基础数据
 *
 * *********************************************************/
import api from 'axios'
import {
  CPageNode,
  CComponentTreeItem, CComponentTreeNode,
  CDataNode, CPropsNode, CMotionNode, CEventNode,
  CBorder,
  CPosition,
  CShape,
  CGraphEntity
} from 'stores/editorModels';

import { useEditorStore } from 'stores/editorStore';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import { uivBaseUrlAPI } from 'src/util/UivBaseConst';


//*****************************************************************************
//          某个页面组件查询、修改
//1.从sca_component,sca_component_props,sca_component_data中读与写
//
//*****************************************************************************
// 模板组件原始数据结构
type CModComponentTreeItem = CComponentTreeItem;
type CModComponentTreeItemVO = CComponentTreeNode;

//接收时传递参数
export interface CModPageInfo {
  page: CPageNode,
  components: CComponentTreeNode[],

  createTime?: any,
  createUserId?: number,
  updateTime?: any,
  updateUserId?: number
}

export function useEditorExecModPageComponent () {
  //store
  const store = useEditorStore();

  //消息通知
  const {
    showMessage,
    showSuccessMessage
  } = useMessageNotify();

  //将数据中读取数据，生成graphEntity对象
  const makeModComponent = (item: CModComponentTreeItemVO): CGraphEntity => {
    let component: CGraphEntity = {
      id: 0,
      typeId: 0,
      pageId: 0,
      comLabel: '',
      comValue: '',
      comSid: '',

      position: {} as CPosition,
      shape: {} as CShape,
      border: {} as CBorder,
      propsItem: [] as CPropsNode[],
      dataItem: [] as CDataNode[],
      motionItem: [] as CMotionNode[],
      eventItem: [] as CEventNode[]
    } as CGraphEntity;

    component.id = item.id;
    component.typeId = item.typeId;
    component.pageId = item.pageId;
    component.comLabel = item.comLabel;
    component.comValue = item.comValue;
    component.comSid = item.comSid;

    (component.position as CPosition).x = item.left;
    (component.position as CPosition).y = item.top;
    (component.position as CPosition).w = item.width;
    (component.position as CPosition).h = item.height;

    (component.shape as CShape).backgroundColor = item.backgroundColor;
    (component.shape as CShape).opacity = item.opacity;
    (component.shape as CShape).visible = item.visible;
    (component.shape as CShape).zIndex = item.zindex;
    (component.shape as CShape).transform = item.transform;

    (component.border as CBorder).width = item.borderWidth;
    (component.border as CBorder).radius = item.borderRadius;
    (component.border as CBorder).line = item.borderLine;
    (component.border as CBorder).color = item.borderColor;

    component.minWidth = item.minWidth;
    component.minHeight = item.minHeight;

    //props属性
    if ((item.propsItem) && (item.propsItem.length > 0)) {
      item.propsItem.forEach((el) => {
        component.propsItem?.push(el);
      })
    }


    return component;
  }


  //将数据保存到数据库
  const saveModuleCurrentPage = () => {
    let pageId = store.canvas.id;
    if (pageId <= 0) {
      showMessage('页面ID出错！');
      return;
    }

    //组件打包发送
    let size = store.components.length;
    let list = [];

    //先处理删除队里里的组件
    clearModuleCurrentPageComponents();

    //页面数据
    let pim: CPageNode = {
      id: store.canvas.id,
      typeId: store.canvas.typeId,
      imgUrl: store.canvas.imgUrl,
      cname: store.canvas.cname,
      backgroundColor: store.canvas.backgroundColor,
      backgroundImage: store.canvas.backgroundImage,
      resolution: store.canvas.resolution,
      width: store.canvas.width,
      height: store.canvas.height,
      wsAddr: store.canvas.wsAddr,
      wsPort: store.canvas.wsPort,
      sortCode: store.canvas.sortCode,
      projectId: store.project.id,
      description: store.canvas.description
    };

    //分批发送存储，每批最多5个
    for (let i = 0;  i < size; i++) {
      //组件基本信息
      let component: CModComponentTreeItem = {
        id: store.components[i].id,
        typeId: store.components[i].typeId,
        pageId: store.components[i].pageId,
        comLabel: store.components[i].comLabel,
        comValue: store.components[i].comValue,
        comSid: store.components[i].comSid,

        left: store.components[i].position.x,
        top: store.components[i].position.y,
        width: store.components[i].position.w,
        height: store.components[i].position.h,

        backgroundColor: store.components[i].shape.backgroundColor,
        opacity: store.components[i].shape.opacity,
        visible: store.components[i].shape.visible,
        zindex: store.components[i].shape.zIndex,
        transform: store.components[i].shape.transform,

        borderWidth: store.components[i].border.width,
        borderRadius: store.components[i].border.radius,
        borderLine: store.components[i].border.line,
        borderColor: store.components[i].border.color,

        minWidth: store.components[i].minWidth,
        minHeight: store.components[i].minHeight,
        propsItem: [],
        dataItem: [],
        motionItem: [],
        eventItem: []
      };

      //组件props属性
      if (store.components[i].propsItem) {
        store.components[i].propsItem?.forEach((item) => {
          let propsItem: CPropsNode = {
            id: item.id,
            label: item.label,
            propName: item.propName,
            value: item.value,
            dataTypeId: item.dataTypeId,
            formTypeId: item.formTypeId,
            optionId: item.optionId
          };

          //插入数组
          component.propsItem?.push(propsItem);
        })
      }


      //插入list数组
      list.push(component);
    }

    //axios发送
    api.post(uivBaseUrlAPI.UIV_MOD_PAGE_SAVE_API, {
      page: pim,
      components: list,
      createTime: '2020-02-13 09:30:44',
      createUserId: 55,
      updateTime: '2020-02-15 09:40:24',
      updateUserId: 100
    }).then((res) => {
      if (res.data.message === 'Success') {
        showSuccessMessage('保存页面组件');

        //更新页面及组件
        let r: CModPageInfo = res.data.data;
        //console.log(r);

        //读取画布信息
        store.initCanvas();
        let ca : CPageNode = r.page;
        store.setCanvas(ca);

        //读取组件信息
        store.initComponents();
        r.components.forEach((item) => {
          //数据库读取组件，id,pageId,sid均从数据库中读取
          let myItem = makeModComponent(item);
          store.addComponents(myItem);
        })
      } else {
        showMessage(res.data.message);
      }
    }).catch((error) => {
      showMessage(error.message);
    })
  };


  //读取当前模板所有组件
  const getModuleCurrentPage = () => {
    let pageId: number = store.canvas.id;
    if (pageId <= 0) {
      showMessage('页面ID出错！');
      return;
    }

    //读取页面组件
    api.post(uivBaseUrlAPI.UIV_MOD_PAGE_LIST_API, {
      id: pageId
    }).then((res: any) => {
      if (res.data.message === 'Success') {
        let r: CModPageInfo = res.data.data;
        //console.log(r);

        //读取画布信息
        store.initCanvas();
        let ca : CPageNode = r.page;
        store.setCanvas(ca);

        //读取组件信息
        store.initComponents();
        r.components.forEach((item) => {
          //数据库读取组件，id,pageId,sid均从数据库中读取
          let myItem = makeModComponent(item);
          store.addComponents(myItem);
        })
      } else {
        //console.log('get component！')
        showMessage(res.data.message);
      }
    }).catch((error) => {
      showMessage(error.message);
    });
  }


  //清空删除队列里的组件
  const clearModuleCurrentPageComponents = () => {
    //axios发送
    if (store.deletedList.length > 0) {
      api.post(uivBaseUrlAPI.UIV_MOD_PAGE_REMOVE_API, {
        ids: store.deletedList
      }).then((res) => {
        if (res.data.message === 'Success') {
          //清空存储数组
          store.initDeletedList();
          showSuccessMessage('删除页面组件');
        } else {
          showMessage(res.data.message);
        }
      }).catch((error) => {
        showMessage(error.message);
      })
    }
  };

  return {
    saveModuleCurrentPage,
    getModuleCurrentPage
  };
}
